<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <el-button type="primary" icon="el-icon-plus" @click="addTrademark">添加</el-button>
      </template>
      <template>
        <el-table
         v-loading="loading"
          stripe
          border
          style="width: 100%"
          :data='trademarks'
          >
          <el-table-column
            type="index"
            label="序号"
            align='center'
            width="80">
          </el-table-column>
          <el-table-column
            prop="tmName"
            label="品牌"">
          </el-table-column>
          <el-table-column
            label="品牌Logo"
            align='center'>
              <template v-slot="{row,$index}">
                <el-image :src="row.logoUrl" alt="logo" style="height: 80px;"></el-image>
              </template>
          </el-table-column>
          <el-table-column
            label="操作">
              <template v-slot="{row}">
                <hint-button title="修改" type="warning" size="small" icon="el-icon-edit" @click="showUpdate(row)"></hint-button>
            <hint-button title="删除" type="danger" size="small" icon="el-icon-delete" @click="remove(row)"></hint-button>
              </template>
          </el-table-column>
        </el-table>
      </template>
      <template>
        <el-pagination
          @current-change='handleCurrentChange'
          @size-change='handleSizeChange'
          style='margin-top:20px;text-align:center;'
          :page-sizes="[5, 10, 15]"
          :page-size="100"
          :current-page='page'
          :total="total"
          layout=" prev, pager, next, jumper,->, sizes,total"
         >
        </el-pagination>
      </template>
      <template>
        <el-dialog :title="`${form.id ? '修改': '添加'}品牌`" :visible.sync="dialogFormVisible" >
          <el-form ref="tmForm" :model="form" label-width="20%" style="width:90%" :rules="rules">
            <el-form-item required label="品牌名称" prop="tmName">
              <el-input v-model="form.tmName" placeholder="请输入品牌名称"></el-input>
            </el-form-item>
            <!--
                action:指定处理上传请求图片的url 存在跨域问题
                http://39.98.123.211:8216/admin/product/fileUpload
                :show-file-list="false"   显示单张图片
              -->
            <el-form-item label="品牌LOGO" prop="logoUrl">
              <el-upload
                class="avatar-uploader"
                action="/dev-api/admin/product/fileUpload"
                :show-file-list="false"  
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar"> <!--如果有值显示图片,没值显示图标+-->
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过50kb</div>
              </el-upload>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="addOrUpdate" :loading="saveLoading">确 定</el-button>
          </div>
      </el-dialog>
      </template>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "TrademarkList",
  data() {
    return {
      trademarks: [], // 当有页列表
      page: 1, // 当前页码
      pageSize: 5,
      total: 0, // 总数量
      loading: false, //请求是否加载中
      dialogFormVisible: false,
      form: {
        name: "",
        logoUrl: "",
      },
      saveLoading: false, 
      rules:{
        tmName: [
          // 声明式校验:利用内置的校验规则进行校验,不需要自己进行判断
            { required: true, message: '请输入品牌名称', trigger: 'blur' },
            // { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'change' }
          // 自定义校验: 通过校验器配置指定校验函数来亲自判断
          { validator: this.validateTmName, trigger: 'blur' }
          ],
        logoUrl:{
          required: true, message: '请上传logo图片', trigger: 'blur' 
        }
      },
    };
  },
  methods:{
    //对品牌名进行自定义校验函数
    /*
    value:品牌名称值
    callback:用来指定检验是否通过的函数
    callback():校验通过
    callback(error.message):校验通过

    */
    validateTmName(rule, value, callback){
      if (value.length<2 || value.length>10 ) {
          callback('长度在 2 到 10 个字符');
        } else {
          callback();
        }
    }
  },
  mounted() {
    // 初始化列表 请求数据
    this.getList();
  },
  methods: {
    //添加品牌
    addTrademark() {
      this.form={
        name: "",
        logoUrl: "",
      }
      // 显示提示框
      this.dialogFormVisible = true; // 更新页面后,并不会直接同步更新界面,而是最后异步更新
      this.$nextTick(()=>{
        this.$refs.tmForm.clearValidate()
      })
    },
    // 修改品牌
    updateTrademark(trademark) {
      // this.form = trademark; 
      // console.log(trademark.logoUrl);
      this.form={...trademark} // 浅拷贝 防止连同data里form里的数据一同修改掉
      this.dialogFormVisible = true;
    },
    // 添加或修改品牌
    addOrUpdate(){
      // 点击确定完成全部校验
      this.$refs['tmForm'].validate( async(valid) => {
        if (valid) {
           try{
              const {form} =this
           this.saveLoading= true, 
          await this.$API.trademark[form.id ? 'update' : 'add'](form)
           // 提示成功
            this.$message({
              type: 'success',
              message: `${form.id ? '更新' : '添加'}成功`
            })
            this.dialogFormVisible = false
            // 关闭dialog
          this.dialogFormVisible = false;
          // 重新获取分页列表: 如果是更新是当前页, 如果是添加是第一页
            if (!form.id) {
              this.page = 1
            }
            this.getList()
           }finally { // 异步请求成功或失败最终都会执行
            this.saveLoading = false // 隐藏loading
          }
          }
         
        });
    },



    // 监听当前页码数量变化
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      // 更新当前页码为1
      this.page = 1;
      // 请求获取当前页码的列表数据
      this.getList();
    },
    // 监听当前页码
    handleCurrentChange(currentPage) {
      this.page = currentPage;
      this.getList();
    },
    async getList() {
      this.loading = true;
      const res = await this.$API.trademark.getList(this.page, this.pageSize);
      console.log(res);
      const { records, total } = res.data;
      this.loading = false;
      this.trademarks = records;
      this.total = total;
    },
    handleAvatarSuccess(res) {
      // 得到上传后的图片url并存起来
      this.form.logoUrl=res.data
      // this.$refs.tmFome.validateField('logoUrl')
      this.$refs.tmForm.clearValidate('logoUrl')

    },
    beforeAvatarUpload(file) {
      const isJPGOrPNG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt50kb = file.size /  1024 <= 50;

      if (!isJPGOrPNG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      }
      if (!isLt50kb) {
        this.$message.error("上传头像图片大小不能超过 50kb!");
      }
      // 只有类型或大小都满足时才返回㹖true
      return isJPGOrPNG && isLt50kb;
    },
  }
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style lang="scss" scoped>
</style>
